package com.fsc.app_news;

import java.io.ByteArrayOutputStream;
import java.io.InputStream;
import java.net.HttpURLConnection;
import java.net.URL;
import java.util.List;

import com.fsc.app_bean.News;
import com.fsc.app_bean.News_Image;
import com.fsc.app_video.ImageLoader;
import com.google.gson.Gson;
import com.google.gson.reflect.TypeToken;

import android.app.Activity;
import android.content.Intent;
import android.os.Bundle;
import android.os.Handler;
import android.view.View;
import android.view.View.OnClickListener;
import android.view.ViewGroup;
import android.widget.BaseAdapter;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.ListView;
import android.widget.TextView;
import android.widget.Toast;

public class NewPageActivity extends Activity implements OnClickListener {
	protected static final int WHAT_REQUEST_SUCCESS = 1;
	protected static final int WHAT_REQUEST_ERROR = 2;
	private ImageView iv_back;
	private TextView tv_news;
	private Intent intent;
	private TextView tv_news_content;
	
	//动态加载图片
	private ListView lv_image;
	private LinearLayout ll_image_loading;
	private News_Image image;
	private List<News_Image> data;
	private ImageAdapter adapter;
	
	private Handler handler = new Handler(){
		public void handleMessage(android.os.Message msg) {
			switch (msg.what) {
			case WHAT_REQUEST_SUCCESS:
				ll_image_loading.setVisibility(View.GONE);
				//显示列表
				lv_image.setAdapter(adapter);
				break;
			case WHAT_REQUEST_ERROR:
				ll_image_loading.setVisibility(View.GONE);
				Toast.makeText(NewPageActivity.this, "加载数据失败", 1).show();
			break;

			default:
				break;
			}
		};
	};
	@Override
	protected void onCreate(Bundle savedInstanceState) {
		super.onCreate(savedInstanceState);
		setContentView(R.layout.new_page);
		init();
		envet();
		/******************************/
		adapter = new ImageAdapter();
		
		/*
		 * 实现联网异步加载图片
		 */
		//1.主线程，显示提示视图
		ll_image_loading.setVisibility(View.VISIBLE);
		//2.分线程，实现联网请求
		new Thread(){
			public void run() {
				try {
					//2)联网请求得到jsonString
					String jsonString = requestJson();
					//3.)解析成List<News_Image>
					data = new Gson().fromJson(jsonString, new TypeToken<List<News_Image>>(){}.getType());
					//3. 主线程, 更新界面
					handler.sendEmptyMessage(WHAT_REQUEST_SUCCESS);//发请求成功的消息
				} catch (Exception e) {
					e.printStackTrace();
					handler.sendEmptyMessage(WHAT_REQUEST_ERROR);//发送请求失败的消息
				}
			};
		}.start();
	}
	//实现联网的方法
	private String requestJson() throws Exception{
		String result = null;
		String path = "http://192.168.43.28:8080/News/NewsServlet";
		//1.得到连接对象
		URL url = new URL(path );
		HttpURLConnection connection = (HttpURLConnection) url.openConnection();
		//2.设置
		connection.setConnectTimeout(5000);
		connection.setReadTimeout(5000);
		//3.连接
		connection.connect();
		//4.发送请求并读取服务器返回的数据
		int code = connection.getResponseCode();
		if(code == 200){
			InputStream is = connection.getInputStream();
			ByteArrayOutputStream baos = new ByteArrayOutputStream();
			byte[] buffer = new byte[1024];
			int len = -1;
			while ((len = is.read(buffer))!=-1) {
				baos.write(buffer, 0, len);
			}
			//关闭流
			baos.close();
			is.close();
			connection.disconnect();
			result = baos.toString();
		}
		return result;
	}
	public void init(){
		iv_back = (ImageView) findViewById(R.id.iv_back);
		tv_news = (TextView) findViewById(R.id.tv_news);
		lv_image = (ListView) findViewById(R.id.lv_image);
		ll_image_loading = (LinearLayout) findViewById(R.id.ll_image_loading);
		tv_news_content = (TextView) findViewById(R.id.tv_news_content); 
	}
	public void envet(){
		iv_back.setOnClickListener(this);
		
		intent = getIntent();
		if (intent  != null){
			tv_news.setText(intent.getStringExtra("Title"));
			tv_news_content.setText(intent.getStringExtra("Content"));
		}
//		tv_news.getPaint().setFlags(Paint. UNDERLINE_TEXT_FLAG ); //下划线
//		tv_news.getPaint().setAntiAlias(true);//抗锯齿
	}
	@Override
	public void onClick(View v) {
		switch (v.getId()) {
		case R.id.iv_back:
			finish();
			break;

		default:
			break;
		}
	}
	/****************加载适配器*********************/
	class ImageAdapter extends BaseAdapter{
		private ImageLoader imageLoader;
		public ImageAdapter() {
			imageLoader = new ImageLoader(NewPageActivity.this, R.drawable.loading, R.drawable.error);
		}
		@Override
		public int getCount() {
			return data.size();
		}

		@Override
		public Object getItem(int position) {
			return data.get(position);
		}

		@Override
		public long getItemId(int position) {
			return 0;
		}

		@Override
		public View getView(int position, View convertView, ViewGroup parent) {
			ViewHolder hodler = null; 
  	        if(convertView == null)  
  	        {  
  	        	hodler = new ViewHolder();
  	        	convertView = View.inflate(NewPageActivity.this, R.layout.item_newpage, null);
  	           
  	            hodler.image = (ImageView) convertView.findViewById(R.id.tv_news_image);
  	            convertView.setTag(hodler);         //表示给View添加一个格外的数据，  
  	        } else {  
  	        	hodler = (ViewHolder) convertView.getTag();//通过getTag的方法将数据取出来  
  	        } 
  	       image = data.get(position);
  	        String imagePath = image.getImagepath();
			//根据图片路径启动分线程动态请求服务加载图片并显示
			imageLoader.loadImage(imagePath, hodler.image); 
  	        return convertView;
		}
	}
	public class ViewHolder {
		private ImageView image;
	}
}
